<?php include "../public/header.php"?>
<script type="text/javascript" src="../../static/admin/xlsx/xlsx.full.min.js"></script>
<script type="text/javascript" src="../../static/admin/xlsx/xlsxyulan.js"></script>
<style>
    .layui-fluid > .layui-form{margin-bottom: 0!important;}
    .layui-form-checkbox[lay-skin=primary]{padding-left: 0}
    .layui-form-checkbox[lay-skin=primary] i{width: 18px;height: 18px;}
    #import_pre{width: 180px;position: absolute;left: 0;top: 0;opacity: 0;cursor: pointer;}
</style>
<body>
<div class="layui-fluid" style="margin-bottom: 0!important;">
    <button class = "layui-btn" type="button" style="width: 180px;background-color: #248BFE">点击选择要导入的文件<input id="import_pre" type="file"/></button>
    <div style="font-size: 14px;margin-top: 30px"></div>
    <div class="layui-form" id="import_con" onscroll="import_onscroll()" style="margin-top:20px;overflow: auto;height: 485px"></div>
    <form class="layui-form"></form>
</div>
<div style="height: 60px;width:100%;position:fixed;bottom:0;text-align:right;background:#e3e3e3;line-height:60px;left: 0">
    <span id="import_error" style="float: left;color:red;font-size: 14px;margin-left: 20px"></span>
    <button class="layui-btn post_sub" style="padding:0 20px;background:#248BFE;" type="button">保存数据</button>
    <button class="layui-btn layui-btn-primary post_cancel" onclick="close_curr()" style="margin-right:20px;padding:0 20px;">取消</button>
</div>
<script type="text/javascript">
    var param_header_obj = getQueryVariable('header_obj');
    var param_call_func = getQueryVariable('call_func');
    var fieldArr = parent.window[param_header_obj];
    var file_qingname = '';

    $("#import_pre").change(function () {
        var loading = layui.layer.load(0, {shade: 0.1});
        let fd = new FormData();
        fd.append('file', this.files[0]);
        fd.append('token', facade.getCookie('token'));
        $.ajax({
            url: server_api_name+ask_main_getgong,
            type: "POST",
            data: fd,
            contentType: false,
            processData: false,
            dataType: "json",
            success: function (e) {
                layui.layer.close(loading);
                if (e.code === 2000) {
                    var data = e.data.data;
                    var sheetContent = '';
                    for (var key in data){
                        sheetContent += '<p data-id="'+key+'" class="import_chioce_sheet" style="cursor: pointer;font-size: 14px;">'+data[key]+'</p>';
                    }
                    let _close_index = layer.open({
                        title: '请选择要导入的Sheet工作表',
                        content: sheetContent,
                        area: ['60%', '60%'],
                        btn: ['取消'],
                        yes: function(index, layero) {
                            layer.close(index);
                        }
                    });
                    render_from();


                    $(".import_chioce_sheet").click(function () {
                        var myMsg = layer.msg("数据加载中，请稍候...",{
                            icon:16,
                            time:-1
                        });
                        var sheetid = $(this).data('id');
                        file_qingname = $(this).text();



                        facade.ajax({type: 'post', url: ask_main_getfile,data:{sheetid:sheetid,filename:e.data.filename,ext:e.data.ext}}).done(function(e){
                            if (e.code === 2000) {
                                layer.close(myMsg);
                                layer.close(_close_index);
                                render_from();
                                file_dump_data(e.data.data, e.data.qingArr, e.data.defield, fieldArr);

                            }
                        });

                    });
                }
            },
            error: function (res) {
                layui.layer.close(loading);
                facade.error("网络错误");
            },
        })













    })


    $(".post_sub").unbind("click").bind("click", function () {
        var selectArr = [];     // [ ['key'=>2,'field'=>'realname']]
        var selectName = [];
        var select_error = '';
        var select_obj = $("#preview_table>thead>tr>th>select");
        for (var i = 0; i < select_obj.length; i++) {
            //var currName = select_obj[i].value;
            var currName = $(select_obj[i]).val();
            var currText = $(select_obj[i]).find("option:selected").text();
            var currKey = $(select_obj[i]).parent().attr('key');
            if (currName) {
                if (selectName.indexOf(currName) == -1) {
                    selectName.push(currName);
                    var lin_obj = {};
                    lin_obj.key = currKey;
                    lin_obj.field = currName;
                    selectArr.push(lin_obj);
                } else {
                    select_error = currText + "重复";
                    break;
                }
            }
        }
        if (select_error != '') {
            layer.msg(select_error);
            return;
        }
        if (selectArr.length < 1) {
            layer.msg("请选择要导入的字段");
            return;
        }

        for (i = 0; i < fieldArr.length; i++) {
            if (fieldArr[i].ismust == 1) {
                if (selectName.indexOf(fieldArr[i].field) == -1) {
                    select_error = "表头中带 * 的为必选字段";
                    break;
                }
            }
        }
        if (select_error != '') {
            layer.msg(select_error);
            return;
        }


        //获取数据
        var contentTr = $("#preview_table>tbody>tr");
        var return_data = [];
        for (i = 0; i < contentTr.length; i++) {
            var hang_obj = {};
            var inputArr = $(contentTr[i]).children('td');
            var ishaveChecked = $(inputArr[0]).find("input[name='ishave']").is(':checked');
            if(!ishaveChecked){
                continue;
            }
            for (var j = 0; j < selectArr.length; j++) {
                var curKey = selectArr[j].key;
                var curField = selectArr[j].field;
                for (var ii = 0; ii < inputArr.length; ii++) {
                    if ($(inputArr[ii]).children('input').attr('key') == curKey) {
                        hang_obj[curField] = $(inputArr[ii]).children('input').val();
                    }
                }
                hang_obj['datatype'] = $(contentTr[i]).find(".hangsele").val();
                hang_obj['hang'] = parseInt(i)+1;
            }
            if (JSON.stringify(hang_obj) != "{}") {
                return_data.push(hang_obj);
            }
        }

        //检查行类型
        var checkFenbu = '';
        var checkZimu = '';
        var checkError = '';
        for (var mm in return_data) {
            if(mm == 0){
                if(return_data[0].datatype != '分部行'){
                    checkError = '第'+return_data[0].hang+'行，行类型错误';
                    layer.msg(checkError);return false;
                }
            }else{
                if(return_data[mm].datatype == '分部行'){
                    if(return_data[mm-1].datatype == '分部行'){
                        checkError = '第'+return_data[mm].hang+'行，行类型错误';
                        layer.msg(checkError);return false;
                    }
                }
                if(return_data[mm].datatype == '子分部行'){
                    if(return_data[mm-1].datatype == '清单行'){
                        if(checkFenbu == '' || checkZimu == ''){
                            checkError = '第'+return_data[mm].hang+'行，行类型错误';
                            layer.msg(checkError);return false;
                        }
                    }
                    if(return_data[mm-1].datatype == '子分部行'){
                        checkError = '第'+return_data[mm].hang+'行，行类型错误';
                        layer.msg(checkError);return false;
                    }
                }


            }
            if(return_data[mm].datatype == '分部行'){
                checkFenbu = return_data[mm].enname;
                checkZimu = '';
            }
            if(return_data[mm].datatype == '子分部行'){
                checkZimu = return_data[mm].enname;
            }

            if(return_data[mm].datatype == '清单行'){
                return_data[mm].fenname = checkFenbu;
                return_data[mm].ziname = checkZimu;
            }
        }
        if(checkError){
            return false;
        }

        parent.window[param_call_func](file_qingname, return_data, fieldArr);
        close_curr();
    })



    function file_dump_data(data_json, qingArr, defield, select_data){
        var hangArr = ['无效行','分部行','子分部行','清单行'];

        $("#import_con").empty();
        var tablehtml = "";
        tablehtml +='<p style="color: red">如数据有误，请单击表格修改</p>';
        tablehtml +='<table id="preview_table" style="width:100%;border: 1px solid #aaa;" border="1">';
        tablehtml +='<thead>';
        tablehtml +='<tr style="height:35px;">';
        //<div class="layui-form-item" pane=""><div class="layui-input-block"><input type="checkbox" name="like1[write]" lay-skin="primary" title="写作" checked=""></div></div>

        // tablehtml += '<th style="text-align: center;width: 48px">';
        // tablehtml += '<div class="layui-input-line">';
        // tablehtml += '<input type="checkbox" name="like1[write]" lay-skin="primary" title=""></div>';
        // tablehtml += '</th>';
        tablehtml += '<th style="text-align: center;min-width: 40px"></th>';
        tablehtml += '<th style="text-align: center;min-width: 40px">行号</th>';
        tablehtml += '<th style="text-align: center;min-width: 100px">行类型</th>';
        for(var key in qingArr){
            var select_html = '';
            select_html = '<select class="import_header_select" name="import_select" style="height: 35px;border: none;min-width: 120px">';
            select_html += '<option value="">未识别</option>';
            for (var i=0; i<select_data.length; i++){
                var must_html = '';
                var xing_html = '';
                if(select_data[i].ismust == 1){
                    must_html = 'style="color: red"';
                    xing_html = '*';
                }
                if(str_in_array(key,defield)){
                    if(qingArr[key] == select_data[i].name){
                        select_html += '<option value="'+select_data[i].field+'" type="'+select_data[i].type+'" '+must_html+' selected>'+xing_html+select_data[i].name+'</option>';
                    }else{
                        select_html += '<option value="'+select_data[i].field+'" type="'+select_data[i].type+'" '+must_html+'>'+xing_html+select_data[i].name+'</option>';
                    }
                }else{
                    select_html += '<option value="'+select_data[i].field+'" type="'+select_data[i].type+'" '+must_html+'>'+xing_html+select_data[i].name+'</option>';
                }
            }
            select_html += '</select>';
            if(qingArr[key] == '项目名称'){
                tablehtml +='<th  key="'+key+'" style="text-align:center;min-width:200px">'+select_html+'</th>';
            }else if(qingArr[key] == '项目特征描述'){
                tablehtml +='<th  key="'+key+'" style="text-align:center;min-width:200px">'+select_html+'</th>';
            }else{
                tablehtml +='<th  key="'+key+'" style="text-align:center;min-width:100px">'+select_html+'</th>';
            }
        }
        tablehtml +='</tr>';
        tablehtml +='</thead>';
        tablehtml +='<tbody>';

        //获取内容
        for(var i = 0; i < data_json.length;i++){
            tablehtml +='<tr style="height:35px;">';
            var xuhao = i+1;
            tablehtml += '<td style="text-align: center;">';
            tablehtml += '<div class="layui-input-line">';
            if(data_json[i]['hang'] != '无效行'){
                tablehtml += '<input type="checkbox" name="ishave" lay-skin="primary" checked></div>';
            }else{
                tablehtml += '<input type="checkbox" name="ishave" lay-skin="primary" disabled></div>';
            }
            tablehtml += '</td>';

            tablehtml += '<td style="text-align: center;">'+xuhao+'</td>';
            var hangStr = '';
            // if(data_json[i]['hang'] == '无效行'){
            //
            //     tablehtml +='<td><input key="" style="width: 100%;text-align:center;height:35px;border:0;color:red" type="text" value="'+data_json[i]['hang']+'"></td>';
            // }else{
            //     tablehtml +='<td><input key="" style="width: 100%;text-align:center;height:35px;border:0;" type="text" value="'+data_json[i]['hang']+'"></td>';
            // }

            tablehtml += '<td class="hangseletd"><select class="hangsele" style="height: 35px;border: none;min-width: 120px" lay-filter="hangsele">';
            for (var mm in hangArr){
                if(data_json[i]['hang'] == hangArr[mm]){
                    tablehtml += '<option value="'+hangArr[mm]+'" selected>'+hangArr[mm]+'</option>';
                }else{
                    tablehtml += '<option value="'+hangArr[mm]+'">'+hangArr[mm]+'</option>';
                }
            }
            tablehtml += '</select></td>';


            for(var key in qingArr){
                tablehtml +='<td><input key="'+key+'" style="width: 100%;text-align:center;height:35px;border:0;" type="text" value="'+data_json[i][key]+'"></td>';
            }
            tablehtml +='</tr>';
        }
        tablehtml +='</tbody>';
        tablehtml +='</table>';
        $("#import_con").append(tablehtml);

        layui.use(['form','table'],function(){
            var form = layui.form;
            form.on('select(hangsele)', function(data){
                if(data.value ==="无效行"){
                    $(data.elem).parents('tr').find('input[name="ishave"]').prop('disabled',true).prop("checked", false);
                    $(data.elem).next().find('input').css('color', 'red')
                }else{
                    $(data.elem).parents('tr').find('input[name="ishave"]').prop('disabled',false).prop("checked", true);
                    $(data.elem).next().find('input').css('color', 'black')
                }
                form.render("checkbox");
            })
            form.render("select");
            form.render("checkbox");
        });

        $('.hangseletd input').each(function (i) {
            if($(this).val() =='无效行'){
                $(this).css('color','red');
            }
        });
    }

    function close_curr() {
        var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
        parent.layer.close(index); //再执行关闭
    }

</script>
</body>
</html>
